package com.sj.purchase.modules.cost.config.task.synchronizedata;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sj.purchase.modules.cost.domain.price.SkuAvgPriceId;
import com.sj.purchase.modules.cost.repository.order.SkuAvgPriceRepository;
import com.sj.purchase.modules.cost.repository.stock.SkuStockRepository;
import com.sj.purchase.modules.cost.domain.stock.SkuStock;
import com.sj.purchase.modules.cost.domain.stock.SkuStockId;
import com.sj.purchase.modules.cost.domain.price.SkuAvgPrice;
import com.sj.purchase.modules.cost.service.stock.StockCostService;
import com.sj.purchase.util.StockUtils;
import com.sj.purchase.util.DateUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 库存
 * Created by yangrd on 2017/7/24.
 */
@Deprecated
@Component
public class StockTask {

	private static final Logger LOGGER = LoggerFactory.getLogger(StockTask.class);

	@Autowired
	private SkuStockRepository skuStockRepository;

	@Autowired
	private StockCostService stockCostService;

	@Autowired
	private SkuAvgPriceRepository skuAvgPriceRepository;

	@Value("${sj.wms}")
	private String wmsApi;

	private static String FORMAT = "yyyy-MM-dd";

	@Autowired
	private RestTemplate restTemplate;

	/**
	 * 同步wms库存，需要wms同步管易时间（01:10开始）完成后执行
	 *
	 * @param day
	 */
//	@Scheduled(cron = "0 10 2 * * ?")
	public void synchronizeWmsStock(Date day) {
		synchronizeWmsStock(DateFormatUtils.format(day, FORMAT));
	}

	@Transactional
	public void synchronizeWmsStock(String day) {
		String url = wmsApi + "/goods/getInventory";
		JSONArray jsonArray = restTemplate.getForObject(url, JSONArray.class);
		List<SkuStock> list = new ArrayList<>(2500);
		for (int i = 0; i < jsonArray.size(); i++) {
			JSONObject stock = jsonArray.getJSONObject(i);
			String sku = stock.getString("skuNo");
			JSONArray warehouses = stock.getJSONArray("warehouse");
			for (int j = 0; j < warehouses.size(); j++) {
				JSONObject warehouse = warehouses.getJSONObject(j);
				String name = warehouse.getString("name");
				long num = warehouse.getLong("num");
				SkuStockId skuStockId = new SkuStockId();
				skuStockId.setWarehouse(StockUtils.getWarehouse(name));
				DateFormat fmt =new SimpleDateFormat(FORMAT);
				Date date = null;
				try {
					date = fmt.parse(day);
					//因为此处的时间为昨天 而起初为今天所有在今天的基础上+1天
					date = DateUtils.addDays(date,1);
				} catch (ParseException e) {
					e.printStackTrace();
				}
				skuStockId.setCreateDate(date);
				skuStockId.setSkuNo(sku);
				SkuStock skuStock = new SkuStock().setId(skuStockId).setNum(num);
				list.add(skuStock);
			}
		}
		skuStockRepository.save(list);
	}

	/**
	 * 每天凌晨计算昨日的库存成本，前提条件：昨日的库存信息，入库单，出库单，sku平均价已同步完毕。
	 */
//	@Scheduled(cron = "0 0 1 * * ?")//todo 基本数据全了，测试上线后展开
	public void synchronizeStockCost(String day) {
		DateFormat fmt =new SimpleDateFormat(FORMAT);
		try {
			Date date = fmt.parse(day);
			synchronizeStockCost(date);
		} catch (ParseException e) {
			e.printStackTrace();
			LOGGER.error("库存成本 日期格式化有误");
		}
	}

	public void synchronizeStockCost(Date day) {
		stockCostService.calculateStockCost(DateUtils.getStartOfDay(day));
	}

	/**
	 * 同步某天平均价
	 *
	 * @param day
	 */
	public void synchronizeSkuAvgCost(String day) {
		String url = wmsApi + "/goods/getSkuCost?dateTime=" + day;
		JSONArray jsonArray = new RestTemplate().getForObject(url, JSONArray.class);
		List<SkuAvgPrice> list = new ArrayList<>(1024);
		for (int i = 0; i < jsonArray.size(); i++) {
			JSONObject skuPrice = jsonArray.getJSONObject(i);
			String sku = skuPrice.getJSONObject("id").getString("skuNo");
			Date date = skuPrice.getJSONObject("id").getDate("createTime");
			double cost = skuPrice.getDouble("cost");
			cost = new BigDecimal(cost).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
			list.add(new SkuAvgPrice().setId(new SkuAvgPriceId().setDay(date).setSkuNo(sku)).setPrice(cost));
		}
		skuAvgPriceRepository.save(list);
	}


}
